/**
 * @Description:
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 27/01/25 AM9:37
 */
import { type StateTree } from 'pinia'
import { aes } from '@shared/utils/secure'
import profile from '@root/profile.ts'
import { parseJsonNoError } from 'sf-utils2'

/* disable-eslint */

/**
 * @param fn
 * @param option
 */
function execTimeLogWrap(fn: Function, option?: { label?: string }): () => any {
  const timeLabel = `[${option?.label || 'execTimeLogWrap'}]执行时间`
  console.time(timeLabel)
  try {
    return function () {
      return fn.apply(this, arguments)
    }
  } finally {
    console.timeEnd(timeLabel)
  }
}

/**
 * 加解密
 */
export const serializer = {
  /**
   * 逆序列化
   * @param value
   */
  deserialize: execTimeLogWrap(
    (value: string) => {
      if (profile.IS_PRO) value = aes.decrypt(value)
      return parseJsonNoError(value) as unknown as StateTree
    },
    { label: 'deserialize' }
  ),

  /**
   * 序列化
   * @param value
   */
  serialize: execTimeLogWrap(
    (value: StateTree) => {
      let result = JSON.stringify(value)
      if (profile.IS_PRO) result = aes.encrypt(result)
      return result
    },
    { label: 'serializer' }
  )
}
